package com.edu.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器，实现用户权限鉴别
 *
 * @author YJF
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 全局拦截
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 用户如果是登录或者一些不需要做权限认证的请求，直接放行
        String uri = request.getURI().toString();
        if (!UrlFilter.hasAuthorize(uri)) {
            return chain.filter(exchange);
        }
        // 获取用户令牌信息
        // 1）头文件中
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        // true: 令牌在头文件中
        boolean hasToken = true;
        // 2）参数获取令牌
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
            hasToken = false;
        }
        // 3）Cookie中
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        // 如果没有令牌，则拦截
        if (StringUtils.isEmpty(token)) {
            // 设置没有权限的状态码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应空数据
            return response.setComplete();
        }
        // 令牌为空，则允许访问，直接拦截
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        } else {
            if (!hasToken) {
                // 判断当前令牌是否有bearer前缀，如果没有，则添加前缀bearer
                if (!token.startsWith("bearer ") && !token.startsWith("Bearer ")) {
                    token = "bearer " + token;
                }
                // 将令牌封装到头文件中
                request.mutate().header(AUTHORIZE_TOKEN, token);
            }
        }
        // 有效放行
        return chain.filter(exchange);
    }

    /**
     * 排序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
